<?php

namespace App\Http\Model;

use HugCode\PhpUnits\InstanceTool;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{

    use InstanceTool;

    public $timestamps = true;

    protected $casts = [
        'UpdateTime' => 'timestamp',
        'CreateTime' => 'timestamp',
    ];

    protected $dateFormat = 'U';

    const CREATED_AT = 'CreateTime';
    const UPDATED_AT = 'UpdateTime';

    /**
     * @desc:  获取表名
     * @Author: yashuai
     */
    public static function tableName()
    {
        return self::instance()->getTable();
    }

    /**
     * @Desc 查询一行记录
     * @param int $id
     * @param string $key
     * @param string $select
     * @return \Illuminate\Database\Query\Builder|mixed
     * @author yashuai
     */
    public static function getInfo($id = 0, $key = 'id', $select = '*')
    {
        $result = self::query()->where([$key => $id])->select($select)->first();
        return empty($result) ? [] : $result->toArray();
    }

    /**
     * @Desc 验证记录否存在
     * @param int $id
     * @param string $key 建名
     * @param bool $status 验证状态
     * @param string $select 查询字段
     * @param string $msg 提示信息
     * @return array|\Illuminate\Database\Query\Builder|mixed
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public static function recordExist($id = 0, $key = 'ID', $status = false, $select = '*', $msg = '')
    {
        if ($status !== false && is_array($select) && !in_array($status, $select)) {
            $select[] = $status;
        }
        $info = self::getInfo($id, $key, $select);
        if (empty($info) || ($status !== false && $info[$status] != ConstCode::BASIC_STATUS_NORMAL)) {
            _throw(106001, $msg);
        }
        return $info;
    }

    /**
     * @Desc 插入
     * @param array $data
     * @return bool|int
     * @author yashuai
     */
    public static function newInsert($data = [])
    {
        if (is_array(reset($data))) {
            foreach ($data as &$item) {
                $item['CreateTime'] = time();
            }
            self::query()->insert($data);
            return true;
        } else {
            $data['CreateTime'] = time();
            return self::query()->insertGetId($data);
        }
    }
}
